import type { RouteRecordRaw } from 'vue-router';


export default function useRouterHelp() {
    /**
 * 转换文件路径为路由路径
 * @example 'views/user/[id]/index.vue' => '/user/:id'
 */
function transformPath(filePath: string): string {
    return filePath
      .replace('../views/', '/')
      .replace(/\/index\.vue$/, '')
      .replace(/\[(\w+)\]/g, ':$1')
  }
/**
 * 生成嵌套路由结构
 */
function createNestedRoutes(
  modules: Record<string, () => Promise<any>>,
  parentPath = ''
): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  const pathMap: Record<string, RouteRecordRaw> = {}

  // 先处理所有路径，建立映射关系
  Object.keys(modules).forEach((filePath) => {
    const routePath = transformPath(filePath)
    const segments = routePath.split('/').filter(Boolean)
    const currentPath = `/${segments.join('/')}`
    const path =  segments[segments.length - 1].startsWith(':')
    ? segments[segments.length - 1]
    : segments.join('/');

    pathMap[currentPath] = {
      path: `/${path}`,
      component: modules[filePath],
      meta: {},
    }
  })
  // 构建嵌套结构
  Object.keys(pathMap).forEach((fullPath) => {
    const segments = fullPath.split('/').filter(Boolean)
    let currentRoutes = routes
    let currentPath = ''

    segments.forEach((segment, index) => {
      currentPath += `/${segment}`
      const isLast = index === segments.length - 1
      const existingRoute = currentRoutes.find(
        (r) => r.path === segment
      )

      if (existingRoute) {
        if (isLast) {
          // 合并现有路由配置
          Object.assign(existingRoute, pathMap[fullPath])
        } else {
          // 进入下一级
          existingRoute.children = existingRoute.children || []
          currentRoutes = existingRoute.children
        }
      } else {
        const newRoute: any = {
          ...(pathMap[fullPath] || {}),
          path: segment,
          ...(isLast ? {} : { children: [] }),
        }

        currentRoutes.push(newRoute)
        if (!isLast) {
          currentRoutes = newRoute.children!
        }
      }
    })
  })

  return routes
}
/**
 * 生成扁平化路由 (可选)
 */
function createFlatRoutes(
  modules: Record<string, () => Promise<any>>
): RouteRecordRaw[] {
  return Object.keys(modules).map((filePath) => {
    const routePath = transformPath(filePath)
    return {
      path: routePath,
      name: routePath,
      component: modules[filePath],
      meta: {},
    }
  })
}
/**
 * 自动生成路由配置
 * @param type string [flat/nexted]
 */
function generateAutoRoutes(type = 'flat') {
  const modules = import.meta.glob('../views/**/index.vue', { eager: false });

  if ('flat' === type) {
    return createFlatRoutes(modules);
  }
  return createNestedRoutes(modules);
}

/**
 * 自动生成嵌套路由配置
 * @returns 生成的路由配置数组【name = path】
 */
function generateRoutes(): RouteRecordRaw[] {
  // 1. 获取所有views目录下的index.vue文件
  const modules = import.meta.glob('../views/**/index.vue', { eager: false })
  
  // 2. 创建路由树结构
  const routeTree: RouteRecordRaw[] = []
  
  // 3. 处理每个模块路径
  for (const filePath in modules) {
    // 解析路径为路由路径格式
    const normalizedPath = filePath
      .replace('../views', '')
      .replace('/index.vue', '')
      .replace(/\[(\w+)\]/g, ':$1') // 转换 [param] 为 :param
    
    // 分割路径为数组
    const pathParts = normalizedPath.split('/').filter(Boolean)
    
    // 从最外层开始构建路由树
    let currentLevel = routeTree
    
    for (let i = 0; i < pathParts.length; i++) {
      const part = pathParts[i]
      const isDynamic = part.startsWith(':')
      const normalizedPart = isDynamic ? part : part.toLowerCase()
      
      // 查找是否已存在该路径段的路由
      let existingRoute = currentLevel.find(
        route => route.path === normalizedPart
      )
      
      // 如果不存在则创建新路由
      if (!existingRoute) {
        const routeName = pathParts
          .slice(0, i + 1)
          .join('-')
          .replace(/:/g, '') // 移除动态参数前的冒号
        
        existingRoute = {
          path: normalizedPart,
          name: routeName || 'home',
          component: i === pathParts.length - 1 
            ? modules[filePath] 
            : i === 0 
              ? () => import('@/layout/index.vue') 
              : undefined,
          children: [],
          meta: {}
        }
        
        currentLevel.push(existingRoute)
      }
      
      // 如果是最后一部分，添加组件和可能的元数据
      if (i === pathParts.length - 1) {
        // 处理可能的动态导入模块
        if (modules[filePath] && typeof (modules[filePath] as any).then === 'function') {
          existingRoute.component = modules[filePath]
        }
        
        // 尝试获取路由元数据
        const module = modules[filePath] as any;
        if (module?.routeMeta) {
          existingRoute.meta = module.routeMeta
        }
      }
      
      // 进入下一层级
      if (existingRoute.children) {
        currentLevel = existingRoute.children
      } else {
        existingRoute.children = []
        currentLevel = existingRoute.children
      }
    }
  }
  
  // 4. 后处理：确保根路径有布局组件
  routeTree.forEach(rootRoute => {
    if (!rootRoute.component && rootRoute.children?.length) {
      rootRoute.component = () => import('@/layout/index.vue')
    }
  })
  
  return routeTree
}

/**
 * 自动生成嵌套路由配置（包含完整路径）
 * @returns 生成的路由配置数组
 */
function generateNestedRoutes(): RouteRecordRaw[] {
  const modules = import.meta.glob('../views/**/index.vue', { eager: false })
  const routeTree: RouteRecordRaw[] = []

  for (const filePath in modules) {
    const normalizedPath = filePath
      .replace('../views', '')
      .replace('/index.vue', '')
      .replace(/\[(\w+)\]/g, ':$1')

    const pathParts = normalizedPath.split('/').filter(Boolean)
    let currentRoutes = routeTree
    let fullPath = ''

    for (let i = 0; i < pathParts.length; i++) {
      const part = pathParts[i]
      const isDynamic = part.startsWith(':')
      const normalizedPart = isDynamic ? part : part.toLowerCase()
      fullPath += `/${normalizedPart}`

      // 查找是否已存在该路径段的路由
      let existingRoute = currentRoutes.find(
        route => route.path === fullPath
      )

      if (!existingRoute) {
        const routeName = pathParts
          .slice(0, i + 1)
          .join('_')
          .replace(/:/g, '')

        existingRoute = {
          path: fullPath, // 使用完整路径
          name: routeName || 'home',
          component: i === pathParts.length - 1 
            ? modules[filePath] 
            : undefined,
          children: [],
          meta: {}
        }

        currentRoutes.push(existingRoute)
      }

      // 如果是最后一部分，添加元数据
      if (i === pathParts.length - 1) {
        // vue3 script setup  import()懒加载是静态加载, 当前获取不到 module?.routeMeta，只能异步或者外部配置routeMeta
        const module = modules[filePath] as any;
        if (module?.routeMeta) {
          existingRoute.meta = module.routeMeta
        }
      }

      // 进入下一层级
      if (existingRoute.children) {
        currentRoutes = existingRoute.children
      } else {
        existingRoute.children = []
        currentRoutes = existingRoute.children
      }
    }
  }

  // 后处理：为中间节点添加布局组件
  function processRoutes(routes: RouteRecordRaw[]) {
    routes.forEach(route => {
      // 有子路由的 路由组件配置
      if (route.children?.length && !route.component) {
        // 路由组件重新配置
        route.component = () => import('@/layout/components/parent-router-view/index.vue');
        // 是否父级
        route.meta.isParent = true;
        // 优先查找 index路由页面是否存在，存在则优先redirect
        const target = route.children.find(child => child.path === `${route.path}/index`);
        route.redirect = target?.path ? target?.path : route.children[0]?.path;
  
        // 子路由排序
        route.children.sort((a, b) => {
          // 如果a.path包含route.redirect而b没有，a排在前面
          if (a.path.includes(route.redirect as string) && !b.path.includes(route.redirect as string)) return -1;
          // 如果b.path包含route.redirect而a没有，b排在前面
          if (b.path.includes(route.redirect as string) && !a.path.includes(route.redirect as string)) return 1;
          // 其他情况保持原顺序
          return 0;
        })
      }
      if (route.children) {
        processRoutes(route.children)
      }
    })
  }

  processRoutes(routeTree)
  return routeTree
}


return {createNestedRoutes, createFlatRoutes, generateAutoRoutes, generateRoutes, generateNestedRoutes}
}
